<template>
  <el-dialog
    v-model="dialogVisible"
    title="订单详情"
    width="1000px"
    @close="handleClose"
  >
    <div v-if="order" class="order-detail">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-card class="detail-card">
            <template #header>
              <h4>订单基本信息</h4>
            </template>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="订单编号">
                {{ order.orderNo }}
              </el-descriptions-item>
              <el-descriptions-item label="客户名称">
                {{ order.customerName }}
              </el-descriptions-item>
              <el-descriptions-item label="产品名称">
                {{ order.productName }}
              </el-descriptions-item>
              <el-descriptions-item label="产品规格">
                {{ order.productSpec || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="数量">
                {{ order.quantity }}
              </el-descriptions-item>
              <el-descriptions-item label="单价">
                ¥{{ order.unitPrice }}
              </el-descriptions-item>
              <el-descriptions-item label="总金额">
                <span class="amount-text">¥{{ order.totalAmount }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="申请状态">
                <el-tag :type="getStatusType(order.applicationStatus)">
                  {{ getStatusText(order.applicationStatus) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="收货地址" :span="2">
                {{ order.deliveryAddress }}
              </el-descriptions-item>
              <el-descriptions-item label="联系人">
                {{ order.contactPerson }}
              </el-descriptions-item>
              <el-descriptions-item label="联系电话">
                {{ order.contactPhone }}
              </el-descriptions-item>
              <el-descriptions-item label="订单描述" :span="2">
                {{ order.orderDescription || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="当前步骤">
                {{ order.currentStep || '未开始' }}
              </el-descriptions-item>
              <el-descriptions-item label="当前审批人">
                {{ order.currentApprover || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">
                {{ formatDate(order.createTime) }}
              </el-descriptions-item>
              <el-descriptions-item label="更新时间">
                {{ formatDate(order.updateTime) }}
              </el-descriptions-item>
            </el-descriptions>
          </el-card>
        </el-col>
        
        <el-col :span="8">
          <el-card class="process-card">
            <template #header>
              <h4>流程状态</h4>
            </template>
            <div class="process-flow">
              <div
                v-for="(step, index) in processSteps"
                :key="index"
                class="process-step"
                :class="step.status"
              >
                <div class="step-circle">
                  <el-icon v-if="step.status === 'completed'">
                    <Check />
                  </el-icon>
                  <el-icon v-else-if="step.status === 'current'">
                    <Loading />
                  </el-icon>
                  <el-icon v-else-if="step.status === 'rejected'">
                    <Close />
                  </el-icon>
                  <span v-else>{{ index + 1 }}</span>
                </div>
                <div class="step-content">
                  <div class="step-name">{{ step.name }}</div>
                  <div v-if="step.approver" class="step-approver">
                    审批人：{{ step.approver }}
                  </div>
                  <div v-if="step.comment" class="step-comment">
                    {{ step.comment }}
                  </div>
                </div>
                <div v-if="index < processSteps.length - 1" class="step-arrow">
                  <el-icon><ArrowDown /></el-icon>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button
          v-if="canSubmit"
          type="primary"
          @click="handleSubmit"
        >
          提交审批
        </el-button>
        <el-button
          v-if="canEdit"
          type="warning"
          @click="handleEdit"
        >
          编辑订单
        </el-button>
        <el-button
          v-if="canCancel"
          type="danger"
          @click="handleCancel"
        >
          取消订单
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Check, Close, Loading, ArrowDown } from '@element-plus/icons-vue'
import { submitOrder, cancelOrder } from '../../api/order.js'

export default {
  name: 'OrderDetail',
  components: {
    Check, Close, Loading, ArrowDown
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    order: {
      type: Object,
      default: null
    }
  },
  emits: ['update:visible', 'success', 'edit'],
  setup(props, { emit }) {
    const dialogVisible = ref(false)
    
    // 监听visible变化
    watch(() => props.visible, (visible) => {
      dialogVisible.value = visible
    })
    
    // 监听dialogVisible变化
    watch(dialogVisible, (visible) => {
      emit('update:visible', visible)
    })
    
    // 流程步骤
    const processSteps = computed(() => {
      if (!props.order) return []
      
      const steps = [
        { name: '办事处商务填写', status: 'completed' },
        { name: '地区经理审批', status: 'pending' },
        { name: '大区经理审批', status: 'pending' },
        { name: '市场部审批', status: 'pending' },
        { name: '物流总监审批', status: 'pending' },
        { name: '销售总监审批', status: 'pending' },
        { name: '公司商务审批', status: 'pending' }
      ]
      
      const currentStep = props.order.currentStep
      const status = props.order.applicationStatus
      
      if (status === 'APPROVED') {
        // 所有步骤都已完成
        steps.forEach(step => step.status = 'completed')
      } else if (status === 'REJECTED') {
        // 订单被拒绝，需要找到拒绝的步骤
        if (currentStep === '审批拒绝') {
          // 如果当前步骤是"审批拒绝"，需要根据拒绝原因或其他信息确定拒绝的步骤
          // 这里我们根据订单的拒绝原因或者流程历史来确定
          // 暂时显示所有步骤为pending，拒绝步骤为rejected
          const rejectStepName = getRejectStepName(props.order)
          const rejectIndex = steps.findIndex(step => step.name === rejectStepName)
          
          if (rejectIndex >= 0) {
            // 拒绝步骤之前的步骤都已完成
            for (let i = 0; i < rejectIndex; i++) {
              steps[i].status = 'completed'
            }
            // 拒绝的步骤标记为rejected
            steps[rejectIndex].status = 'rejected'
            // 拒绝步骤之后的步骤保持pending
            for (let i = rejectIndex + 1; i < steps.length; i++) {
              steps[i].status = 'pending'
            }
          } else {
            // 如果找不到拒绝步骤，默认第一个审批步骤被拒绝
            steps[1].status = 'rejected'
          }
        } else {
          // 如果当前步骤不是"审批拒绝"，按原来的逻辑处理
          const currentIndex = steps.findIndex(step => step.name === currentStep)
          for (let i = 0; i < currentIndex; i++) {
            steps[i].status = 'completed'
          }
          if (currentIndex >= 0) {
            steps[currentIndex].status = 'rejected'
          }
        }
      } else if (currentStep && currentStep !== '审批拒绝') {
        // 正常进行中的流程
        const currentIndex = steps.findIndex(step => step.name === currentStep)
        for (let i = 0; i < currentIndex; i++) {
          steps[i].status = 'completed'
        }
        if (currentIndex >= 0) {
          steps[currentIndex].status = 'current'
        }
      }
      
      return steps
    })
    
    // 根据订单信息确定拒绝的步骤
    const getRejectStepName = (order) => {
      // 如果订单有拒绝步骤信息，直接使用
      if (order.rejectStep) {
        return order.rejectStep
      }
      
      // 如果没有拒绝步骤信息，需要根据审批历史或流程状态推断
      // 这里应该从后端获取更准确的拒绝步骤信息
      // 暂时根据流程状态推断：如果订单状态是REJECTED，说明某个审批步骤被拒绝了
      // 需要根据实际的审批历史来确定具体是哪个步骤
      
      // 默认返回地区经理审批（这个逻辑需要根据实际业务调整）
      return '地区经理审批'
    }
    
    // 是否可以提交
    const canSubmit = computed(() => {
      return props.order?.applicationStatus === 'PENDING' && !props.order?.processInstanceId
    })
    
    // 是否可以编辑
    const canEdit = computed(() => {
      return props.order?.applicationStatus === 'PENDING' && !props.order?.processInstanceId
    })
    
    // 是否可以取消
    const canCancel = computed(() => {
      return props.order?.applicationStatus === 'PENDING'
    })
    
    // 获取状态类型
    const getStatusType = (status) => {
      const statusMap = {
        'PENDING': 'warning',
        'APPROVED': 'success',
        'REJECTED': 'danger',
        'CANCELLED': 'info'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'PENDING': '待审批',
        'APPROVED': '已通过',
        'REJECTED': '已拒绝',
        'CANCELLED': '已取消'
      }
      return statusMap[status] || status
    }
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '-'
      return new Date(dateString).toLocaleString()
    }
    
    // 关闭对话框
    const handleClose = () => {
      dialogVisible.value = false
    }
    
    // 提交审批
    const handleSubmit = async () => {
      try {
        await submitOrder(props.order.id)
        ElMessage.success('订单提交成功，已启动审批流程')
        emit('success')
        handleClose()
      } catch (error) {
        console.error('提交订单失败:', error)
        ElMessage.error('提交订单失败')
      }
    }
    
    // 编辑订单
    const handleEdit = () => {
      emit('edit', props.order)
      handleClose()
    }
    
    // 取消订单
    const handleCancel = async () => {
      try {
        const { value: reason } = await ElMessageBox.prompt('请输入取消原因：', '取消订单', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /.+/,
          inputErrorMessage: '取消原因不能为空'
        })
        
        await cancelOrder(props.order.id, reason)
        ElMessage.success('订单已取消')
        emit('success')
        handleClose()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('取消订单失败:', error)
          ElMessage.error('取消订单失败')
        }
      }
    }
    
    return {
      dialogVisible,
      processSteps,
      canSubmit,
      canEdit,
      canCancel,
      getStatusType,
      getStatusText,
      formatDate,
      handleClose,
      handleSubmit,
      handleEdit,
      handleCancel
    }
  }
}
</script>

<style scoped>
.order-detail {
  padding: 0;
}

.detail-card,
.process-card {
  height: 100%;
}

.amount-text {
  font-size: 16px;
  font-weight: bold;
  color: #E6A23C;
}

.process-flow {
  padding: 10px 0;
}

.process-step {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
  position: relative;
}

.step-circle {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  flex-shrink: 0;
  font-size: 14px;
  font-weight: bold;
}

.process-step.completed .step-circle {
  background-color: #67C23A;
  color: white;
}

.process-step.current .step-circle {
  background-color: #409EFF;
  color: white;
  animation: pulse 2s infinite;
}

.process-step.rejected .step-circle {
  background-color: #F56C6C;
  color: white;
}

.process-step.pending .step-circle {
  background-color: #E4E7ED;
  color: #909399;
}

.step-content {
  flex: 1;
  min-width: 0;
}

.step-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.step-approver,
.step-comment {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}

.step-arrow {
  position: absolute;
  left: 15px;
  top: 32px;
  color: #E4E7ED;
  font-size: 12px;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

.dialog-footer {
  text-align: right;
}
</style>
